<template>
  <div class="users-page">
    <el-page-header>
      <template #content>
        <span class="page-title">用户管理</span>
      </template>
    </el-page-header>

    <!-- 操作按钮区域 -->
    <el-card class="operation-card" shadow="never">
      <el-space wrap>
        <el-button type="primary" :loading="loading" @click="loadUsers" :icon="Refresh">
          {{ loading ? '加载中...' : '刷新用户列表' }}
        </el-button>
        <el-button type="success" @click="showAddModal" :icon="Plus">
          添加用户
        </el-button>
      </el-space>

      <!-- 用户统计 -->
      <el-tag v-if="!loading && hasUsers" class="user-stats" type="info" effect="plain">
        <el-icon>
          <User />
        </el-icon>
        共找到 {{ userCount }} 个用户
      </el-tag>
    </el-card>

    <!-- 错误提示 -->
    <el-alert v-if="error" :title="error" type="error" class="error-alert" show-icon closable @close="clearError" />

    <!-- 用户列表 -->
    <el-card v-if="!loading && hasUsers" class="table-card" shadow="never">
      <el-table :data="users" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="姓名" show-overflow-tooltip />
        <el-table-column prop="email" label="邮箱" show-overflow-tooltip />
        <el-table-column label="操作" width="300" align="center">
          <template #default="{ row }">
            <el-space>
              <el-button type="info" size="small" @click="viewUser(row.id)" :icon="View">
                查看详情
              </el-button>
              <el-button type="warning" size="small" @click="editUser(row)" :icon="Edit">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="deleteUser(row.id)" :icon="Delete" :loading="loading">
                删除
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 空状态 -->
    <el-empty v-if="!loading && !hasUsers && !error" description="暂无用户数据" class="empty-state">
      <el-button type="primary" @click="loadUsers">重新加载</el-button>
    </el-empty>

    <!-- 用户详情弹窗 -->
    <el-dialog v-model="showViewDialog" title="用户详情" width="500px" :before-close="closeModal">
      <el-descriptions v-if="selectedUser" :column="1" border>
        <el-descriptions-item label="用户ID">
          <el-tag>{{ selectedUser.id }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="姓名">
          {{ selectedUser.name }}
        </el-descriptions-item>
        <el-descriptions-item label="邮箱">
          <el-link :href="`mailto:${selectedUser.email}`" type="primary">
            {{ selectedUser.email }}
          </el-link>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="closeModal">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑用户弹窗 -->
    <el-dialog v-model="showFormDialog" :title="modalType === 'add' ? '添加用户' : '编辑用户'" width="500px"
      :before-close="closeModal" :close-on-click-modal="false">
      <el-form ref="userFormRef" :model="formData" :rules="formRules" label-width="80px" @submit.prevent="submitForm">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入用户姓名" :disabled="formLoading" clearable />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" type="email" placeholder="请输入用户邮箱" :disabled="formLoading" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-space>
          <el-button @click="closeModal" :disabled="formLoading">
            取消
          </el-button>
          <el-button type="primary" @click="submitForm" :loading="formLoading">
            {{ modalType === 'add' ? '添加' : '更新' }}
          </el-button>
        </el-space>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive, computed } from 'vue'
import { useUserStore } from '@/stores/user'
import { type User } from '@/types/api'
import { storeToRefs } from 'pinia'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  Refresh,
  Plus,
  User as UserIcon,
  View,
  Edit,
  Delete
} from '@element-plus/icons-vue'

// 使用用户store
const userStore = useUserStore()
const { users, loading, error, userCount, hasUsers } = storeToRefs(userStore)
const { fetchUsers, fetchUserById, createUser, updateUser, deleteUser: deleteUserFromStore, clearError } = userStore

// 本地状态
const selectedUser = ref<User | null>(null)
const modalType = ref<'view' | 'add' | 'edit' | null>(null)
const formLoading = ref(false)
const userFormRef = ref<FormInstance>()

// 计算属性用于控制对话框显示
const showViewDialog = computed({
  get: () => modalType.value === 'view',
  set: (val: boolean) => {
    if (!val) closeModal()
  }
})

const showFormDialog = computed({
  get: () => modalType.value === 'add' || modalType.value === 'edit',
  set: (val: boolean) => {
    if (!val) closeModal()
  }
})

// 表单数据
const formData = reactive({
  name: '',
  email: ''
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入用户姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '姓名长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  // email: [
  //   { required: true, message: '请输入邮箱地址', trigger: 'blur' },
  //   { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  // ]
}

// 加载用户数据
const loadUsers = async () => {
  await fetchUsers()
}

// 查看用户详情
const viewUser = async (userId: number) => {
  const user = await fetchUserById(userId)
  if (user) {
    selectedUser.value = user
    modalType.value = 'view'
  }
}

// 显示添加用户模态框
const showAddModal = () => {
  formData.name = ''
  formData.email = ''
  selectedUser.value = null
  modalType.value = 'add'
  // 重置表单验证
  setTimeout(() => {
    userFormRef.value?.resetFields()
  }, 0)
}

// 编辑用户
const editUser = (user: User) => {
  formData.name = user.name
  formData.email = user.email
  selectedUser.value = user
  modalType.value = 'edit'
  // 重置表单验证
  setTimeout(() => {
    userFormRef.value?.resetFields()
  }, 0)
}

// 删除用户
const deleteUser = async (userId: number) => {
  try {
    await ElMessageBox.confirm(
      '此操作将永久删除该用户。是否继续？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    await deleteUserFromStore(userId)
    ElMessage.success('用户删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + (error instanceof Error ? error.message : '未知错误'))
    }
  }
}

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return

  try {
    // 表单验证
    await userFormRef.value.validate()

    formLoading.value = true

    if (modalType.value === 'add') {
      await createUser({
        name: formData.name.trim(),
        email: formData.email.trim()
      })
      ElMessage.success('用户添加成功')
    } else if (modalType.value === 'edit' && selectedUser.value) {
      await updateUser(selectedUser.value.id, {
        name: formData.name.trim(),
        email: formData.email.trim()
      })
      ElMessage.success('用户更新成功')
    }

    closeModal()
  } catch (error) {
    if (error !== false) { // 表单验证失败时error为false
      ElMessage.error('操作失败：' + (error instanceof Error ? error.message : '未知错误'))
    }
  } finally {
    formLoading.value = false
  }
}

// 关闭模态框
const closeModal = () => {
  selectedUser.value = null
  modalType.value = null
  formData.name = ''
  formData.email = ''
  formLoading.value = false
  userFormRef.value?.resetFields()
}

// 页面加载时获取用户数据
onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.users-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.operation-card {
  margin: 20px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-stats {
  margin-left: auto;
}

.error-alert {
  margin: 20px 0;
}

.table-card {
  margin: 20px 0;
}

.empty-state {
  margin: 40px 0;
}

/* 对话框内的表单样式调整 */
.el-form {
  padding: 10px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .users-page {
    padding: 10px;
  }

  .operation-card {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }

  .user-stats {
    margin-left: 0;
    text-align: center;
  }
}
</style>